package com.mes.web.controller.jy;

import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mes.entity.cb.Materiel;
import com.mes.entity.hy.Product;
import com.mes.entity.jy.Queryjy;
import com.mes.entity.jy.Tempma;
import com.mes.entity.jy.Tempproduct;
import com.mes.entity.jy.Wlfc;
import com.mes.entity.tdd.Rejects;
import com.mes.service.jy.CodeServise;
import com.mes.service.jy.GotempkuServise;
import com.mes.service.jy.TempmaService;
import com.mes.service.jy.TempproductServise;
import com.mes.utils.ResponseUtil;

/**
 * @ClassName: TempproductController 
 * @Description:产品线边库
 * @Author jy
 * @Date 2018年3月15日 下午3:41:22 
 * @version 1.0
 */
@Controller
@RequestMapping("/tempproduct")
public class TempproductController {

	@Resource
	private TempproductServise tempproductServise;
	@Resource
	private GotempkuServise gotempkuServise;
	@Resource
	private TempmaService tempmaService;
	@Resource
	private CodeServise codeServise;
	
	
	/**
	 * 查询产品线边库（带条件）
	 * @param queryjy 条件查询实体
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/selectTempProduct")
	public void selectTempProduct(Queryjy queryjy,HttpServletResponse response) throws Exception {
		
		//对接收的查询条件进行判空处理及回显处理
		if (null!=queryjy.getPname()) {
			String pname = queryjy.getPname();
			//判断当前字符串的编码格式
			if(pname.equals(new String(pname.getBytes("iso8859-1"), "iso8859-1")))
			{
				pname =new String(pname.getBytes("iso8859-1"),"utf-8");
			}
			queryjy.setPname(pname);
		}
		//条件查询
		List<Tempproduct> list= tempproductServise.selectTempProduct(queryjy);
		//统计
		int count = tempproductServise.counTempProduct(queryjy);
		for (Tempproduct tempproduct : list) {
			//获取产品id
			String pid = tempproduct.getPid();
			
			queryjy.setPid(pid);
			//根据产品id统计入库数量
			Integer rnum = tempproductServise.countpRnumer(queryjy);
			if(rnum != null) {
				tempproduct.setComeku(rnum+"");
			}
			//查询产品移库单有没有记录
			/*tempproductServise.selectRemove();*/
			
			//根据产品id统计出库数量
			Integer cnum = tempproductServise.countpCnumer(queryjy);
			if(cnum != null) {
				tempproduct.setComeku(rnum+"");
			}
			tempproduct.setGoku(cnum+"");
		}
		
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("total", count);
		jsonObject.put("rows", list);
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 查询所有待入库产品信息给安卓端
	 * @param request 请求
	 * @param response 响应
	 * @return 如果没数据返回空
	 * @throws Exception 异常
	 */
	@RequestMapping("/allProduct")
	public String allItem(HttpServletRequest request,HttpServletResponse response) throws Exception{
		response.setContentType("application/json; charset=utf-8"); 
		
		List<Product> list = new ArrayList<Product>();
		List<Product> list1 = tempproductServise.selectAllProduct();
		List<Product> list2 = tempproductServise.selectAllProduct2();
		list.addAll(list1);
		list.addAll(list2);
		//获得数据
		JSONObject jsonObject = new JSONObject();
		if (list.size()>0) {
			//传递数据到页面
		    jsonObject.put("code", "200");
		    jsonObject.put("message", "");
		    jsonObject.put("results", list);
		}
		ResponseUtil.write(response, jsonObject);
		return null;
	}
	
	/**
	 * 查询所有线边库产品信息给PDA端。
	 * @param request 请求
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/allTempProduct")
	public void allTempProduct(HttpServletRequest request,HttpServletResponse response) throws Exception {
		response.setContentType("application/json; charset=utf-8"); 
		List<Tempproduct> list = tempproductServise.selectallTempProduct();
		
		//获得数据
		JSONObject jsonObject = new JSONObject();
		if (list.size()>0) {
			//传递数据到页面
		    jsonObject.put("code", "200");
		    jsonObject.put("message", "");
		    jsonObject.put("results", list);
		}else {
			//传递数据到页面
		    jsonObject.put("code", "500");
		    jsonObject.put("message", "查询数据为空");
		    jsonObject.put("results", list);
		}
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 查询BOM清单进行BOM计算
	 * @param pnum 产品品编
	 * @param num 数量
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/selectBom")
	public void selectBom(String pnum,String num,HttpServletResponse response) throws Exception {
		response.setContentType("application/json; charset=utf-8");
		
		Integer num1 = Integer.valueOf(num);
		//根据产品编号查询这个产品对应的物料集合
		List<Materiel> list= tempproductServise.selectBomByPnum(pnum);
		//遍历这个集合，物料数量*产品数量 
		if(list.size()>0) {
			for (Materiel materiel : list) {
				Integer mnum = Integer.valueOf(materiel.getRemark9());
				Integer mnum2 = mnum*num1;
				materiel.setRemark9(mnum2+"");
			}
		}
		
		//获得数据
		JSONObject jsonObject = new JSONObject();
		if (list.size()>0) {
			//传递数据到页面
		    jsonObject.put("code", "200");
		    jsonObject.put("message", "");
		    jsonObject.put("results", list);
		}else {
			//传递数据到页面
		    jsonObject.put("code", "500");
		    jsonObject.put("message", "对不起，此产品还没有绑定BOM信息");
		    jsonObject.put("results", list);
		}
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 添加物料反冲记录
	 * @param wlfcs 物料反冲实体
	 * @param code 条码
	 * @param request 请求
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/createWlfc")
	public void createWlfc(String wlfcs,String bomcode, HttpServletRequest request,HttpServletResponse response) throws Exception {

		Gson gson = new Gson();
		
		Date date = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		int affact = 0;
		int mnum  = 0;
		int num = 0;
		List<Wlfc> list = gson.fromJson(wlfcs, new TypeToken<List<Wlfc>>(){}.getType());
		List<String> list2 = gson.fromJson(bomcode, new TypeToken<List<String>>(){}.getType());
		for (Wlfc wlfc1 : list) {
			String format = dateFormat.format(date);
			wlfc1.setDatatime(format);
			
			//删除相对应的线边物料库存或减数量
			//1.根据物料id查询库存中时间最早的那条记录的数量
			Tempma  tempma= tempmaService.selectTempMnumBymid(wlfc1.getMid());
			
			int mcount = tempmaService.selectMakcByMid(wlfc1.getMid());
			mnum = Integer.valueOf(wlfc1.getNum());
			if(mcount < mnum) {
				affact = -1;
			}else {
				//2.比较数量
				if(wlfc1.getNum() != null) {
					
					 mnum = Integer.valueOf(tempma.getRemark4());
					 num = Integer.valueOf(wlfc1.getNum()) ;
					if(mnum > num) {
						//库存数量大于反冲数量直接减
						mnum = mnum - num;
						tempma.setRemark4(mnum+"");
						tempmaService.editMnumByid(tempma);
					}else if(mnum == num) {
						tempmaService.deleteMa(tempma.getId());
					}else if(mnum < num) {
						//库存数量小于反冲数量时，删除库存对应记录，并减反冲数量减去相应数量
						mnum = mnum - num;
						tempmaService.deleteMa(tempma.getId());
						Tempma  tempma2= tempmaService.selectTempMnumBymid(wlfc1.getMid());
						
						if(tempma2.getRemark4() != null) {
							int mnum2 = Integer.valueOf(tempma2.getRemark4());
							
							mnum2 = mnum2 - mnum;
							tempma.setRemark4(mnum2+"");
							tempmaService.editMnumByid(tempma2);
						}else {
							affact = -1;
						}
					}
				}
				
				//根据物料型号查线边库 库存集合，获取条码和批次
				String type = wlfc1.getType();
				if(type != null && type !="") {
					List<Tempma> resutlList= tempproductServise.selectTempMaByType(type);
					wlfc1.setCode(resutlList.get(0).getRemark1());
					wlfc1.setPihao(resutlList.get(0).getRemark());
				}
				
				//循环添加物料反冲记录
				affact = tempproductServise.createWlfc(wlfc1);
			}
		}
		
		for (String s : list2) {
			//添加完要更改线边产品库库存状态（根据状态）
			tempproductServise.editRemark7(s);
		}
		
		net.sf.json.JSONObject jsonObject1 = new net.sf.json.JSONObject();
		if (affact > 0  ) {
			jsonObject1.put("code", "200");
    		jsonObject1.put("message", "反冲成功");
    		jsonObject1.put("results", null);
		}else if(affact == -1) {
			jsonObject1.put("code", "500");
    		jsonObject1.put("message", "反冲失败,库存数量不足");
    		jsonObject1.put("results", null);
		}else {
			jsonObject1.put("code", "500");
    		jsonObject1.put("message", "反冲失败");
    		jsonObject1.put("results", null);
		}
		ResponseUtil.write(response, jsonObject1);
	}
	
	/**
	 * 查询物料反冲列表（带条件的分页查询）
	 * @param queryjy 条件查询
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/selectWlfcList")
	public void selectWlfcList(Queryjy queryjy,HttpServletResponse response) throws Exception {
		
		//对接收的查询条件进行判空处理及回显处理
		if (null!=queryjy.getType()) {
			String type = queryjy.getType();
			//判断当前字符串的编码格式
			if(type.equals(new String(type.getBytes("iso8859-1"), "iso8859-1")))
			{
				type =new String(type.getBytes("iso8859-1"),"utf-8");
			}
			queryjy.setType(type);
		}
		
		//统计物料反冲总记录
		int count = tempproductServise.countWlfc(queryjy);
		
		//查询物料反冲列表
		List<Wlfc> list= tempproductServise.selectWlfcList(queryjy);
		
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("total", count);
		jsonObject.put("rows", list);
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 导入线边产品库
	 * @param request 请求
	 * @param response 响应
	 * @param file 文件
	 * @throws Exception 异常
	 */
	@RequestMapping("/uplodeFile")
    public void uplodeFile(HttpServletRequest request , HttpServletResponse response , @RequestParam(value = "pic", required = false)MultipartFile file) throws Exception {
        //文件是否为空
        if (file == null) {
            return;
        }

        //文件路径
        String  path = request.getSession().getServletContext().getRealPath("/upload");

        //文件名称
        String filename = file.getOriginalFilename();

        InputStream is = file.getInputStream();

        File dir = new File(path,filename);

        if (!dir.exists()) {
            dir.mkdirs();
        }

        file.transferTo(dir);

        int affct = 0;
        Workbook workbook = null;
        // 创建一个表格
        try {
            workbook = new HSSFWorkbook(is);
            // 获得sheet1
        } catch (Exception e) {
            workbook = new XSSFWorkbook(is);
        }

        // 获得sheet1
        Sheet sheet = workbook.getSheetAt(0);
        // 读取每一行数据

        for (Row row : sheet) {

	        int rowNum = row.getRowNum();
	        if (rowNum == 0) {
	            continue;
	        }

            Tempproduct tempproduct = new Tempproduct();
            //产品编号
	    	 
            if(row.getCell(1) != null) {
            	
            	//根据产品编号查询产品id以及判断基础信息中有无此产品信息
            	Product product =  tempproductServise.selectProductByPnum(row.getCell(1).getStringCellValue());
            	if(product != null) {
            		//产品id
            		tempproduct.setPid(product.getPid()+"");
            	}else {
            		affct = -1;
            		return;
            	}
            }
	    	    
    		   //批号
	    	   tempproduct.setRemark(row.getCell(3).getStringCellValue());
	    	   //数量
	    	   if(row.getCell(4)!=null){
	    	          row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
	    	          tempproduct.setRemark2(row.getCell(4).getStringCellValue());
	    	     }
	    	   //条形码
	    	   if(row.getCell(5)!=null){
	    	          row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
	    	          tempproduct.setRemark1(row.getCell(5).getStringCellValue());
	    	    }
	    	   
	    	   //入库时间
	    	   	Date date = new Date();
	   			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	   			String format = dateFormat.format(date);
	   			tempproduct.setDatatime(format);
	    	   //操作人
	   			affct = gotempkuServise.createTempProduct(tempproduct);

        }
        ResponseUtil.write(response,affct);
    }

	 
	 /**
		 * 导入线边资材库
		 * @param request
		 * @param response
		 * @param file
		 * @throws Exception
		 */
		 @RequestMapping("/uplodeFile2")
	    public void uplodeFile2(HttpServletRequest request , HttpServletResponse response , @RequestParam(value = "pic2", required = false)MultipartFile file) throws Exception {
	        //文件是否为空
	        if (file == null) {
	            return;
	        }

	        //文件路径
	        String  path = request.getSession().getServletContext().getRealPath("/upload");

	        //文件名称
	        String filename = file.getOriginalFilename();

	        InputStream is = file.getInputStream();

	        File dir = new File(path,filename);

	        if (!dir.exists()) {
	            dir.mkdirs();
	        }

	        file.transferTo(dir);

	        int affct = 0;
	        Workbook workbook = null;
	        // 创建一个表格
	        try {
	            workbook = new HSSFWorkbook(is);
	            // 获得sheet1
	        } catch (Exception e) {
	            workbook = new XSSFWorkbook(is);
	        }

	        // 获得sheet1
	        Sheet sheet = workbook.getSheetAt(0);
	        // 读取每一行数据

	        for (Row row : sheet) {

		        int rowNum = row.getRowNum();
		        if (rowNum == 0) {
		            continue;
		        }

	            Tempma tempma = new Tempma();
	            //条形码
	            if(row.getCell(0)!=null){
	            	row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
	            	tempma.setRemark1(row.getCell(0).getStringCellValue());
	            }
		    	 
	            //物料型号
	            if(row.getCell(2) != null) {
	            	
	            	//根据物料型号查询物料id以及判断基础信息中有无此产品信息
	            	Materiel materiel =  tempproductServise.selectMaByType(row.getCell(2).getStringCellValue());
	            	if(materiel != null) {
	            		//产品id
	            		tempma.setPid(materiel.getId()+"");
	            	}else {
	            		affct = -1;
	            		return;
	            	}
	            }
    		 
	    	   //数量
	    	   if(row.getCell(4)!=null){
	    	          row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
	    	          tempma.setRemark4(row.getCell(4).getStringCellValue());
	    	     }
	    	   
	    	   //入库时间
	    	   	Date date = new Date();
	   			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	   			String format = dateFormat.format(date);
	   			tempma.setDatatime(format);
	    	   //操作人
	   			affct = tempmaService.createTempMa(tempma);

	        }
	        ResponseUtil.write(response,affct);
	    }

		/**
		 * 带条件的分页查询不良品库存
		 * @param queryjy 条件查询实体
		 * @param response 响应
		 * @throws Exception 异常
		 */
		@RequestMapping("/selectRejectsPagine")
		public void selectRejectsPagine(Queryjy queryjy,HttpServletResponse response) throws Exception {
			
			//对接收的查询条件进行判空处理及回显处理
			if (null!=queryjy.getPname()) {
				String pname = queryjy.getPname();
				//判断当前字符串的编码格式
				if(pname.equals(new String(pname.getBytes("iso8859-1"), "iso8859-1")))
				{
					pname =new String(pname.getBytes("iso8859-1"),"utf-8");
				}
				queryjy.setPname(pname);
			}
			int count = tempproductServise.countReject(queryjy);
			List<Rejects> list = tempproductServise.selectRejectsPagine(queryjy);
			JSONObject jsonObject=new JSONObject();
			jsonObject.put("total", count);
			jsonObject.put("rows", list);
			ResponseUtil.write(response, jsonObject);
		}
		
		/**
		 * 产品入库校验
		 * @param code
		 * @param response
		 * @throws Exception 
		 */
		@RequestMapping("/checkGoTempproduct")
		public void checkGoTempproduct(String code, HttpServletResponse response) throws Exception {
			
			int count = -1;
			String message = "";
			//1.校验条码是否是生产出来的
			int selectCode = codeServise.selectCode(code);
			if(selectCode > 0) {
				//2.校验条码是否已经入库
				count = tempproductServise.countCode(code);
			}
			
			if(count > 0) {
				//已入库
				message = "已入库，请重新扫码";
			}else {
				//未入库
				message = "未入库";
			}
			
			net.sf.json.JSONObject jsonObject1 = new net.sf.json.JSONObject();
			jsonObject1.put("code", "200");
    		jsonObject1.put("message", message);
    		jsonObject1.put("results", count);
    		ResponseUtil.write(response, jsonObject1);
		}
		
		/**
		 * 生产出的不良品   入库
		 * @param rejects
		 * @param request
		 * @param response
		 * @throws Exception 
		 */
		@RequestMapping("/goNoGoodku")
		public void goNoGoodku(String rejects, HttpServletRequest request,HttpServletResponse response) throws Exception {
			Gson gson = new Gson();
			int affact = 0;
			
			System.out.println(rejects);
			List<Rejects> list = gson.fromJson(rejects, new TypeToken<List<Rejects>>(){}.getType());
			for (Rejects rejects2 : list) {
				
				//根据条码查询该条码的  产品id，批次，数量  在线边产品库
				Tempproduct tempproduct = tempproductServise.selectManyByCode(rejects2.getCode());
				
				rejects2.setNum(tempproduct.getRemark2());
				rejects2.setProductid(tempproduct.getPid());
				rejects2.setPici(tempproduct.getRemark());
				affact = tempproductServise.insertRejects(rejects2);
			}
			
			net.sf.json.JSONObject jsonObject1 = new net.sf.json.JSONObject();
			if (affact > 0  ) {
				jsonObject1.put("code", "200");
	    		jsonObject1.put("message", "不良品入库成功");
	    		jsonObject1.put("results", null);
			}else {
				jsonObject1.put("code", "500");
	    		jsonObject1.put("message", "不良品入库失败");
	    		jsonObject1.put("results", null);
			}
			ResponseUtil.write(response, jsonObject1);
		}
		
		
		/**
		 * 不良品入库
		 * @param code
		 * @param response
		 * @throws Exception 
		 */
		@RequestMapping("/checkNoGoodCode")
		public void checkNoGoodCode (String code, HttpServletResponse response) throws Exception {
			
			int count = -1;
			String message = "";
			//1.校验条码是否是生产出来的
			int selectCode = codeServise.selectCode(code);
			if(selectCode > 0) {
				//2.校验条码是否已经入不良品库
				count = tempproductServise.countNoGoodCode(code);
			}
			
			if(count > 0) {
				//已入库
				message = "已入库，请重新扫码";
			}else {
				//未入库
				message = "未入库";
			}
			
			net.sf.json.JSONObject jsonObject1 = new net.sf.json.JSONObject();
			jsonObject1.put("code", "200");
    		jsonObject1.put("message", message);
    		jsonObject1.put("results", count);
    		ResponseUtil.write(response, jsonObject1);
			
		}
}
